package com.yixun.qfbao.hander;

import java.util.*;

import com.yixun.qfbao.enums.QfSmsTemplateEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yixun.qfbao.api.service.ThirdPartyApiService;
import com.yixun.qfbao.apidto.SendVerificationCodeReqDto;
import com.yixun.qfbao.apidto.SendVerificationCodeResDto;
import com.yixun.qfbao.dto.base.BaseRequestDTO;
import com.yixun.qfbao.dto.base.BaseResponseDTO;
import com.yixun.qfbao.hander.base.CommonAbstractHander;
import com.yixun.qfbao.model.Company;
import com.yixun.qfbao.model.dto.CompanyDto;
import com.yixun.qfbao.model.dto.SmsHistoryDto;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import com.yixun.qfbao.model.enums.SMSTypeEnum;
import com.yixun.qfbao.model.enums.SendStatusEnum;
import com.yixun.qfbao.service.CompanyService;
import com.yixun.qfbao.service.SmsHistoryService;
import com.yixun.qfbao.service.SmsSettingService;
import com.yixun.qfbao.util.SMSUtil;
import com.yixun.qfbao.vo.SendVerificationCodeReqVo;
import com.yixun.qfbao.xf.model.enums.ResultEnum;

/**
 * @author guifang.weng
 * @create 2017-12-06 10:00
 **/
@Service
public class SendVerificationCodeHander extends CommonAbstractHander {
    private static Logger logger= LoggerFactory.getLogger(SendVerificationCodeHander.class);

    @Autowired
    private ThirdPartyApiService thirdPartyApiService;
    @Autowired
    private SMSUtil smsUtil;
    @Autowired
    private SmsSettingService smsSettingService;
    @Autowired
    private SmsHistoryService smsHistoryService;
    @Autowired
    private CompanyService companyService;

    @Override
    public BaseResponseDTO doBusiness(BaseRequestDTO reqDto) {
        BaseResponseDTO<SendVerificationCodeResDto> res = new BaseResponseDTO<>();
        SendVerificationCodeReqVo reqVo = (SendVerificationCodeReqVo) reqDto;
        SendVerificationCodeReqDto sendVerificationCodeReqDto = reqVo.getParams();
        String code = Integer.toString(new Random().nextInt(900000)+100000);
        String messageContent = "【分销助手】您的短信验证码是"+ code +",本条短信用于新用户注册，请勿泄露。";
        sendVerificationCodeReqDto.setCode(code);
        sendVerificationCodeReqDto.setMessageContent(messageContent);
        String companyCode = sendVerificationCodeReqDto.getCompanyCode();
        try {
        	//获取短信设置
        	Map<String, String> smsSettingMap = null;
        	//注释此逻辑
        	//smsSettingService.getSmsSettingMap(sendVerificationCodeReqDto.getDomain(), null,sendVerificationCodeReqDto.getCompanyUuid());
        	Map<String,String> qfSmsMap = new HashMap<>();
        	qfSmsMap.put("key1",code);
            Map<String, Object> returnMap =smsUtil.sendMessage(messageContent,sendVerificationCodeReqDto.getPhone(), QfSmsTemplateEnum.SMS_REGISTER_USER.getId(),smsSettingMap,qfSmsMap);
            boolean sendStatus = (Boolean) returnMap.get("sendStatus");
            String sendRes = String.valueOf(returnMap.get("sendRes"));
            sendVerificationCodeReqDto.setSendMsgFlag(sendStatus);
            
            // 根据域名获取公司信息
    		Company company = new Company();
    		CompanyDto cDto = new CompanyDto();
    		cDto.setDomain(sendVerificationCodeReqDto.getDomain());
    		cDto.setCompanyUuid(sendVerificationCodeReqDto.getCompanyUuid());
    		cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
    		List<Company> lists = companyService.selectListByDto(cDto);
    		if (null != lists && lists.size() > 0) {
    			company = lists.get(0);
    		}
    		// 添加短信历史记录
    		SmsHistoryDto history = new SmsHistoryDto();
    		history.setContent(messageContent);
    		history.setReceiver(sendVerificationCodeReqDto.getPhone());
    		if (company != null && company.getId() != null) {
    			history.setMerchantId(company.getId());
    		} else {
    			history.setMerchantId(0L);
    		}
    		history.setSender("qiaofang");
    		if(null != smsSettingMap) {
    			history.setSender(smsSettingMap.get("userName"));
    		}
    		history.setRemark(SMSTypeEnum.TYPE_13.getDes());
    		history.setCreateTime(new Date());
    		history.setCreateUserId(0L);
    		String state = sendStatus == true ? SendStatusEnum.SUCCESS.getNo() : SendStatusEnum.FAILURE.getNo();
    		history.setSendStatus(state);
            history.setSendRes(sendRes);
            if(returnMap.containsKey("orderUuid")){
                history.setOrderUuid(String.valueOf(returnMap.get("orderUuid")));
            }
            if(returnMap.containsKey("platform")){
                history.setPlatform(String.valueOf(returnMap.get("platform")));
            }
    		smsHistoryService.create(history);
            
            SendVerificationCodeResDto resDto = thirdPartyApiService.sendVerificationCode(sendVerificationCodeReqDto);
            res.setResult(resDto.getResult());
            res.setResData(resDto);
        } catch (Exception e) {
            logger.error("SendVerificationCodeHander error: {}", e);
            res.setResult(ResultEnum.FAIL.getNo());
            res.setErrorMsg("发送验证码失败");
        }
        return res;
    }
}
